import React from 'react'
import { HashRouter, Route, Switch } from 'react-router-dom';
import * as FormUtil from '../public/js/formUtil'
import { connect } from 'react-redux'
import * as actions from '../actions'


//同步加载
import AppContainer from '../container/AppContainer/AppContainer'
import MyCompoents from '../container/AppContainer/index'
// import NotFoundPage from '../container/NotFoundPage'


class RootRouter extends React.Component {
  constructor(props) {
    super(props)
  }
  componentDidMount() {
    FormUtil.getDataBySync(domainName + "/menus/me2", {}, (response) => {
      this.props.setRouters(response.routers)
      this.props.setMenus(response.menu)
      setTimeout(()=>{
        this.props.setCurSelMenu(selMenuId)
      },300) 
    })
  }

  renderRouters() {
    let routeArr = [], routers = this.props.routers
    for (let i = 0; i < routers.length; i++) {
      let route = routers[i]
      if (routers[i].defaultPath) {
        routeArr.push((<Route exact path={route['path']} key={'routers_' + route['id']}
          render={({ history, location, match }) => {
            selMenuId = route['menuId']
            let TmpCompent = MyCompoents[route['component']]
            return (<TmpCompent history={ history } location={location} match={match} />)
          }}
        />))
      } else {
        routeArr.push((<Route path={route['path']} key={'routers_' + route['id']}
          render={({ history, location, match }) => {
            selMenuId = route['menuId']
            let TmpCompent = MyCompoents[route['component']]
            return (<TmpCompent history={history} location={location} match={match} />)
          }}
        />))
      }
    }
    return routeArr
  }
  render() {
    setCurMenu = this.props.setCurSelMenu
    return (
      <HashRouter>
        <Switch>
          <Route path="/" render={({ history, location, match }) => {
            return (
              <AppContainer history={history} location={location} match={match}>
                {this.renderRouters()}
              </AppContainer>
            )
          }} />
        </Switch>
      </HashRouter>
    )
  }
}


function mapStateToProps(state) {
  return {
    selMenu: state.selMenu,
    routers: state.routers
  }
}

export default connect(mapStateToProps, actions)(RootRouter);